package com.old.controller;

import com.old.dto.*;
import com.old.entity.User;
import com.old.result.PageBean;
import com.old.result.Result;
import com.old.service.ActivityService;
import com.old.service.PostService;
import com.old.service.UserService;
import com.old.service.VideoService;
import com.old.util.JwtUtil;
import com.old.util.ThreadLocalUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;


@RestController
@Slf4j
@RequiredArgsConstructor
@RequestMapping("/my")
public class    UserCenterController {

    private final UserService userService;
    private final ActivityService activityService;
    private final PostService PostService;

    private final PostService postService;
    private final VideoService videoService;

    @PutMapping("/updateUserInfo")
    public Result updateUserInfo(@RequestBody UserUpdateInfoDTO userUpdateInfoDTO) {
        // 1. 参数校验
        if (userUpdateInfoDTO.getPassword() == null ||
                userUpdateInfoDTO.getAvatar() == null ||
                userUpdateInfoDTO.getName() == null ||
                userUpdateInfoDTO.getUserId()==null ||
                userUpdateInfoDTO.getAccount() == null){
            return Result.error("缺少必要参数");
        }
        //TODO 判定account是否为纯int
        try {
            //试图获取当前登录用户ID
            Map<String, Object> map = ThreadLocalUtil.get();
            Integer userId;
            if (map != null) {
                userId = (Integer) map.get("id");
            }else{
                log.info("线程获取userid失败,改从传入获取");
                userId = userUpdateInfoDTO.getUserId();
            }

            // 更新用户信息
            userService.updateUserInfo(userId, userUpdateInfoDTO);
            log.info("用户信息更新成功，用户ID：{}", userId);

            //重新生成jwt
            User updateUser = userService.findByID(userId);
            if(updateUser == null){
                log.info("用户信息更新后找不到用户");
                return Result.error("用户信息更新后找不到用户");
            }

            Map<String, Object> claims = new HashMap<>();
            claims.put("id", updateUser.getId());
            claims.put("username", updateUser.getName());
            claims.put("avatar", updateUser.getAvatar());
            // 更新线程数据
            ThreadLocalUtil.set(claims);

            String token = JwtUtil.genToken(claims);
            log.info("New_token:{}",token);
            return Result.success(token);

        } catch (Exception e) {
            log.error("用户信息更新失败", e);
            return Result.error("用户信息更新失败");
        }
    }
    //修改用户活动

    @PutMapping("/updateActivityInfo")
    public Result updateActivityInfo(@RequestBody ActivityUpdateDTO activityUpdateDTO) {
        // 1. 参数校验
        if (activityUpdateDTO.getActivityId() == null ||
                activityUpdateDTO.getTitle() == null ||
                activityUpdateDTO.getContent() == null ||
                activityUpdateDTO.getStartTime() == null ||
                activityUpdateDTO.getEndTime() == null ||
                activityUpdateDTO.getIsShow() == null ||
                activityUpdateDTO.getActivityNum() == null ||
                activityUpdateDTO.getActivityPlace() == null) {
            return Result.error("缺少必要参数");
        }

        try {
            // 2. 获取当前登录用户ID
          //  Integer userId = getCurrentUserIdFromToken();
          //  if (userId == null) {
         //       return Result.error("用户未登录");
          //  }

            // 3. 更新活动信息
            activityService.updateActivityInfo(activityUpdateDTO);
            log.info("活动信息更新成功，活动ID：{}", activityUpdateDTO.getActivityId());
            return Result.success();
        } catch (Exception e) {
            log.error("活动信息更新失败", e);
            return Result.error("活动信息更新失败");
        }
    }

    @RequestMapping("/getUserInfo")
    public Result<User> getUserInfo(@RequestParam("userId") Integer userId) {
        log.info("获取{}用户信息",userId);
        User user =  userService.findByID(userId);
        return Result.success(user);
    }

    @RequestMapping("/getMyActivityList")
    public Result<PageBean> getMyActivityList(@RequestParam("userId") Integer userId) {
        log.info("获取{}用户发布活动列表",userId);
        ActivityQueryDTO activityQueryDTO = new ActivityQueryDTO();
//        预制参数-接口文档没写分页查询 提前写了
        activityQueryDTO.setPageNo(1);
        activityQueryDTO.setPageSize(10);
        activityQueryDTO.setSortBy(1);
        activityQueryDTO.setSearchTerms("");
        activityQueryDTO.setAuthorId(userId);

        PageBean pageResult = activityService.activityListPage(activityQueryDTO);
        log.info("活动活动列表查询成功,共{}条,活动内容为:{}",pageResult.getTotal(),pageResult.getList());
        return Result.success(pageResult);
    }

    @RequestMapping("/getMyPostList")
    public Result<PageBean> getMyPostList(@RequestParam("userId") Integer userId) {
        log.info("获取{}用户发布帖子列表",userId);
        PostQueryDTO postQueryDTO = new PostQueryDTO();
//        预制参数-接口文档没写分页查询 提前写了
        postQueryDTO.setSearchTerms("");
        postQueryDTO.setAuthorId(userId);

        PageBean pageResult = PostService.getPostListById(postQueryDTO);
        log.info("发帖列表查询成功,共{}条,发帖内容为:{}",pageResult.getTotal(),pageResult.getList());
        return Result.success(pageResult);
    }

    @RequestMapping("/getMyVideoList")
    public Result<PageBean> getMyVideoList(@RequestParam("userId") Integer userId) {
        log.info("获取{}用户发布戏曲列表",userId);
        VideoQueryDTO videoQueryDTO = new VideoQueryDTO();
//        预制参数-接口文档没写分页查询 提前写了
        videoQueryDTO.setPageNo(1);
        videoQueryDTO.setPageSize(10);
        videoQueryDTO.setSortBy(1);
        videoQueryDTO.setSearchTerms("");
        videoQueryDTO.setAuthorId(userId);
        PageBean pageResult = videoService.getVideoListById(videoQueryDTO);
        log.info("戏曲列表查询成功,共{}条,戏曲内容为:{}",pageResult.getTotal(),pageResult.getList());
        return Result.success(pageResult);
    }

    @DeleteMapping("/deleteVideo")
    public Result deleteVideo(@RequestParam(required = false) Integer videoId,
                              @RequestHeader(required = false,value = "Authorization") String token) {
        // 1. 参数校验
        if (videoId == null) {
            return Result.error("videoId 不能为空");
        }

        try {
            // 2. 获取当前登录用户ID
            Integer userId = JwtUtil.getUserIdFromToken(token);
            if (userId == null) {
                return Result.error("用户未登录");
            }
            // 3. 删除戏曲
            videoService.deleteVideo(videoId,userId);
            log.info("戏曲删除成功，videoId：{}", videoId);
            return Result.success();
        } catch (Exception e) {
            log.error("戏曲删除失败", e);
            return Result.error("戏曲删除失败");
        }
    }

    @DeleteMapping("/deletePost")
    public Result deletePost(@RequestParam(required = false) Integer postId,
                             @RequestHeader(required = false,value = "Authorization") String token) {
        // 1. 参数校验
        if (postId == null) {
            return Result.error("postId 不能为空");
        }

        try {
            // 2. 获取当前登录用户ID
            Integer userId = JwtUtil.getUserIdFromToken(token);
            if (userId == null) {
                return Result.error("用户未登录");
            }
            // 3. 删除帖子
            postService.deletePost(postId,userId);
            log.info("帖子删除成功，postId：{}", postId);
            return Result.success();
        } catch (Exception e) {
            log.error("帖子删除失败", e);
            return Result.error("帖子删除失败");
        }
    }

    @DeleteMapping("/deleteActivity")
    public Result deleteActivity(@RequestParam(required = false) Integer activityId) {
        // 1. 参数校验
        if (activityId == null) {
            return Result.error("activityId 不能为空");
        }

        try {
            // 2. 获取当前登录用户ID
//            Integer userId = getCurrentUserIdFromToken();
//            if (userId == null) {
//                return Result.error("用户未登录");
//            }

            // 3. 删除活动
            activityService.deleteActivity(activityId);
            log.info("活动删除成功，activityId：{}", activityId);
            return Result.success();
        } catch (Exception e) {
            log.error("活动删除失败", e);
            return Result.error("活动删除失败");
        }
    }

    @RequestMapping("/getJoinActivityList")
    public Result<PageBean> getJoinActivityList(Integer userId) {
        log.info("获取{}用户参与活动列表",userId);
        ActivityQueryDTO activityQueryDTO = new ActivityQueryDTO();
//        TODO 预制菜-接口文档没写分页查询 提前写了
        activityQueryDTO.setPageNo(1);
        activityQueryDTO.setPageSize(20);
        activityQueryDTO.setSortBy(1);
        activityQueryDTO.setSearchTerms("");
        activityQueryDTO.setAuthorId(userId);

        PageBean pageResult = activityService.userJoinActivityListPage(activityQueryDTO);
        log.info("查询用户参加活动列表成功,共{}条,活动内容为:{}",pageResult.getTotal(),pageResult.getList());
        return Result.success(pageResult);
    }


}
